package com.example.service.Impl;

import com.example.domain.LoginUser;
import com.example.domain.Result;
import com.example.domain.User;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import com.example.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author 59400
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Result login(User user) {
        //1.认证（使用security自动认证）
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证不成功
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误！");
        }
        //2.认证成功，从认证信息中获取UserId
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        //3.使用jwt生成token
        String jwt = JwtUtil.createJWT(userId);
        //4.用户信息存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);

        return new Result(200,"登录成功",map);
    }

    //退出登录
    @Override
    public Result logout() {
        //1.从SecurityContextHolder获取userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //2.从redis中删除LoignUser
        String redisKey = "login:"+userId;
        redisCache.deleteObject(redisKey);
        return new Result(200,"退出成功！");

    }
}
